package cn.tedu.sp06.fb;

import cn.tedu.web.util.JsonResult;
import org.springframework.cloud.netflix.zuul.filters.route.FallbackProvider;
import org.springframework.http.HttpHeaders;
import org.springframework.http.HttpStatus;
import org.springframework.http.client.ClientHttpResponse;
import org.springframework.stereotype.Component;

import java.io.ByteArrayInputStream;
import java.io.IOException;
import java.io.InputStream;

/**Hystrix 断路器
 * 当调用后台的商品服务失败.
 * 执行网关中的这个降级类,向客户端返回降级结果
 * zuul默认已经启动了Hystrix
 * 添加降级:
 * 	1.添加降级类,实现FallbackProvider接口
 * 	2.添加 @Component
 */
@Component
public class OrderFB implements FallbackProvider {
    /**
     * 设置当前降级类,针对哪个后台服务降级
        -order-service:只针对商品降级
        -*:  对所有服务都应用当前降级类
        -null: 对所有服务都应用当前降级类
     */
    @Override
    public String getRoute() {
        return "order-service";//指针对哪个服务进行降级
    }

    //发回给客户端的降级响应数据
    @Override
    public ClientHttpResponse fallbackResponse(String route, Throwable cause) {
        return new ClientHttpResponse() {

            public HttpHeaders getHeaders() {
                HttpHeaders headers = new HttpHeaders();
                headers.add("Content-Type", "application/json;charset=UTF-8");
                return headers;
            }


            public InputStream getBody() throws IOException {
                String json = JsonResult.build().code(500).msg("调用后台服务失败").toString();
                //将json串封装到输入流里
                ByteArrayInputStream inputStream = new ByteArrayInputStream(json.getBytes("UTF-8"));
                return inputStream;
            }


            //返回的状态
            public HttpStatus getStatusCode() throws IOException {
                return HttpStatus.INTERNAL_SERVER_ERROR;
            }

            //状态码
            public int getRawStatusCode() throws IOException {
                return 0;
            }

            //状态文本
            public String getStatusText() throws IOException {
                return null;
            }


            public void close() {
                //用来关闭下面的输入流
                //ByteArrayInputStream 不占用底层系统资源,不需要关闭
            }
        };
    }



}
